// 固定租金 分成租金 管理费
<template>
  <div class="padding-right-15">
    <el-collapse accordion v-model="activeNames">
      <el-collapse-item name="1">
        <template slot="title">
          <span class="font-size-16 font-weight-700 padding-right-10">{{ title }}</span>
          <!-- <el-button type="text" class="margin-right-15" v-if="$route.query.contractType == 'ZL'" @click.stop="fillFirstPaymentDate">自动填充首次付款时间</el-button> -->
          <i v-if="isEdit" class="header-icon el-icon-plus" @click.stop="addItem"></i>
        </template>
        <el-table :border="true" :data="tableList">
          <el-table-column align="center" label="资产" v-if="$route.query.contractType == 'ZL' && pageName != 'shareRentList'" width="140px">
            <template slot-scope="scope">
              <el-select class="yj-input" :disabled="!isEdit" v-model="scope.row.shopKey" placeholder="请选择" @change="setAssetArea(scope.row)">
                <template v-for="item in selfAssetsList">
                  <el-option v-if="item.assetKey" :key="item.assetKey" :label="item.assetName" :value="item.assetKey"></el-option>
                </template>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="阶段" width="120px">
            <template slot-scope="scope">
              <el-select class="yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.stageNum" placeholder="请选择" @change="changeStage(scope.row)">
                <el-option v-for="(item, i) in stageList" :key="i" :label="item.label" :value="item.key"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="开始时间" width="155px">
            <template slot-scope="scope">
              <el-date-picker type="date" :disabled="isDisabled(scope.row)" value-format="timestamp" class="no-border-input yj-input" v-model="scope.row.rentStartDate" @change="changeTime(scope.row, 'start')" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="付款周期" width="130px">
            <template slot-scope="scope">
              <el-select class="yj-input" v-if="scope.row.stageNum == 0 || scope.row.stageNum == 1000" :disabled="isDisabled(scope.row)" v-model="scope.row.collectionCycle" placeholder="请选择" @change="changePeriod(scope.row)">
                <el-option v-for="item in periodList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"> </el-option>
              </el-select>
              <el-select class="yj-input" v-else :disabled="disableFirstDate(scope.row, 'collectionCycle')" v-model="scope.row.collectionCycle" placeholder="请选择" @change="changePeriod(scope.row)">
                <el-option v-for="item in provideObj.periodList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="结束时间" width="155px">
            <template slot-scope="scope">
              <el-date-picker type="date" :disabled="isStartEndDateDisabled(scope.row)" value-format="timestamp" class="no-border-input yj-input" v-model="scope.row.rentEndDate" @change="changeTime(scope.row, 'end')" />
              <!-- <el-date-picker v-if="scope.row.collectionCycle == 0" type="date" :disabled="isStartEndDateDisabled(scope.row)" value-format="timestamp" class="no-border-input" v-model="scope.row.rentEndDate" /> -->
              <!-- <el-select class="yj-input" v-else :disabled="isStartEndDateDisabled(scope.row)" v-model="scope.row.rentEndDate" placeholder="请选择">
                <el-option v-for="(item, index) in scope.row.endList" :key="index" :value="item" :label="formDataDate(item)"></el-option>
              </el-select> -->
            </template>
          </el-table-column>
          <el-table-column align="center" label="首次付款时间" width="155px">
            <template slot-scope="scope">
              <el-date-picker v-if="scope.row.stageNum == 0 || scope.row.stageNum == 1000" type="date" :disabled="isDisabled(scope.row)" value-format="timestamp" class="no-border-input yj-input" v-model="scope.row.firstPaymentDate" />
              <el-date-picker v-else type="date" :disabled="disableFirstDate(scope.row, 'firstPaymentDate')" value-format="timestamp" class="no-border-input yj-input" v-model="scope.row.firstPaymentDate" />
            </template>
          </el-table-column>
          <el-table-column align="center" label="指导单价" v-if="$route.query.contractType == 'ZL'" width="130px">
            <template slot-scope="scope">
              <el-input-number :controls="false" class="no-border-input yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.guideUnitPrice"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column v-if="pageType == 'shareRent'" align="center" label="比例">
            <template slot-scope="scope">
              <el-input-number :controls="false" class="no-border-input yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.shareProportion"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :label="pageName == 'shareRentList'? '预计单价' : '计费单价'" align="center">
            <el-table-column label="金额" align="center" width="130px">
              <template slot-scope="scope">
                <el-input-number :controls="false" class="no-border-input yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.calculateUnitPrice" @blur="setMoney(scope.row, 'unit')"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" width="130px">
              <template slot-scope="scope">
                <el-select class="yj-input" v-if="$route.query.contractType == 'ZL'" :disabled="isDisabled(scope.row)" v-model="scope.row.calculateUnit" placeholder="请选择" @change="setMoney(scope.row, 'unit')">
                  <el-option v-for="(item, i) in optionObj.rentCalculateUnit" :key="i" :label="item.value" :value="item.key"></el-option>
                </el-select>

                <el-select class="yj-input" v-if="$route.query.contractType == 'WRSB'" :disabled="isDisabled(scope.row)" v-model="scope.row.calculateUnit" placeholder="请选择">
                  <el-option v-for="(item, i) in optionObj.deviceCalculateUnit" :key="i" :label="item.value" :value="item.key"></el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column :label="pageName == 'shareRentList' ? '预计金额' : '固定金额'" align="center">
            <el-table-column label="金额(含税)" align="center" width="170px">
              <template slot-scope="scope">
                <el-input-number :controls="false" class="no-border-input yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.fixedPriceIncludeTax" @blur="setMoney(scope.row)"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" width="130px">
              <template slot-scope="scope">
                <el-select class="yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.fixedUnit" placeholder="请选择" @change="setMoney(scope.row)">
                  <template v-for="(item, i) in optionObj.rentFixedUnit">
                    <el-option v-if="scope.row.collectionCycle != '0' && item.key != 'rent_fixed_total_unit'" :key="i" :label="item.value" :value="item.key"></el-option>
                    <el-option v-if="scope.row.collectionCycle == '0' && item.key == 'rent_fixed_total_unit'" :key="i" :label="item.value" :value="item.key"></el-option>
                  </template>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="金额(不含税)" align="center" width="170px">
              <template slot-scope="scope">
                <el-input-number :controls="false" class="no-border-input yj-input" :disabled="isDisabled(scope.row)" v-model="scope.row.fixedPriceExcludeTax"></el-input-number>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column align="center" label="操作" v-if="isEdit">
            <template slot-scope="scope">
              <el-button type="text" @click="deleteItem(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>
<script>
  import { accMul, accAdd, monthDayDiff, getLastDay, formDataDate } from '@/common/js/utils.js';
  import { apiRateList, apiGetGuideUnitPrice } from '../../api/contract';
  import { contractCost, Calculate } from '../../mixin/contractCost';
  import util from '@/common/js/utils.js';
  import dayjs from 'dayjs';
  import lodash from 'lodash';

  export default {
    mixins: [contractCost],
    props: {
      title: {
        type: String,
        default: '',
      },
      isEdit: {
        type: Boolean,
        default: true,
      },
      pageType: {
        type: String,
        default: '',
      },
      pageName: {
        type: String,
        default: '',
      },
      selfAssetsList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      optionObj: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },

    inject: ['provideObj'],

    data() {
      return {
        tableList: [],
        stageList: [], //阶段
        activeNames: ['1'],
        rate: 0,
        formObj: {
          stageNum: '',
          rentStartDate: '',
          rentEndDate: '',
          shopKey: '',
          collectionCycle: '',
          firstPaymentDate: '',
          guideUnitPrice: undefined,
          shareProportion: undefined,
          calculateUnitPrice: undefined,
          calculateUnit: this.$route.query.contractType == 'ZL' ? 'rent_calculate_day_unit' : 'device_calculate_day_unit',
          fixedPriceIncludeTax: undefined,
          fixedUnit: 'rent_fixed_month_unit',
          fixedPriceExcludeTax: undefined,
          shopName: '',
          shopCode: '',
          endList: [],
        },
        dateList: [],
        formDataDate: formDataDate,
        periodList: [{ dictKey: '0', dictValue: '一次性' }],
      };
    },

    computed: {
      //校验首次付款时间可填
      disableFirstDate() {
        return (val, type) => {
          if (!this.isEdit) {
            return true;
          } else {
            if (val.stageNum == 0 || val.stageNum == 1000) {
              return false;
            } else {
              let list = this.tableList.filter(item => item.shopKey == val.shopKey);
              list = lodash.remove(list, function (item) {
                return item.rentStartDate && item.stageNum != 0 && item.stageNum != 1000;
              });
              list = lodash.sortBy(list, function (item) {
                return item.rentStartDate;
              });
              //判断首次付款时间的是否可填
              if (type == 'firstPaymentDate' && list && list.length > 0) {
                if (val.rentStartDate > list[0].rentStartDate) {
                  val.firstPaymentDate = '';
                  return true;
                } else {
                  return false;
                }
              }
              //判断付款周期的是否可填
              if (type == 'collectionCycle' && list && list.length > 0) {
                if (val.rentStartDate > list[0].rentStartDate) {
                  val.collectionCycle = list[0].collectionCycle;
                  return true;
                } else {
                  return false;
                }
              }
            }
          }
        };
      },
      //通用校验可填
      isDisabled() {
        return val => {
          if (!this.isEdit) {
            return true;
          } else {
            if (this.$route.query.contractType == 'ZL') {
              if (this.pageName == 'shareRentList') {
                return false;
              } else {
                return val.shopKey ? false : true;
              }
            } else {
              return false;
            }
          }
        };
      },
      isStartEndDateDisabled() {
        return val => {
          if (!this.isEdit) {
            return true;
          } else {
            return val.collectionCycle ? false : true;
          }
        };
      },
    },

    methods: {
      //查税数据源
      async getRateList() {
        let res = await apiRateList();
        res.rows.forEach(item => {
          if (item.primaryKey == this.pageType) {
            this.rate = Number(item.taxRate);
          }
        });
      },

      //改变周期
      changePeriod(row) {
        if (row.collectionCycle != '0' && row.fixedUnit == 'rent_fixed_total_unit') row.fixedUnit = '';
        if (row.collectionCycle == '0' && row.fixedUnit != 'rent_fixed_total_unit') row.fixedUnit = 'rent_fixed_total_unit';
        row.rentEndDate = '';
        this.getEndDate(row);
      },

      //每一行的开始结束时间必须在所选资产的周期范围内
      changeTime(row, type) {
        let lock = this.validateDate(row);
        if (!lock) return;
        let assetTarget = this.selfAssetsList.filter(item => item.assetKey == row.shopKey);
        let asset = assetTarget && assetTarget.length > 0 ? assetTarget[0] : {};
        if (type == 'start') {
          if (row.rentStartDate < asset.rentStartDate || row.rentStartDate > asset.rentEndDate) {
            row.rentStartDate = '';
            this.$message.warning('请检查对应资产周期时间，应在其范围内！');
            return;
          }
          //计算结束时间
          this.getEndDate(row);
          row.rentEndDate = '';
        }
        if (type == 'end') {
          if (row.rentEndDate > asset.rentEndDate || row.rentEndDate < asset.rentStartDate) {
            row.rentEndDate = '';
            this.$message.warning('请检查对应资产周期时间，应在其范围内！');
            return;
          }
        }
        this.setMoney(row, 'unit');
      },

      //改变阶段
      changeStage(row) {
        if ((row.stageNum == 0 || row.stageNum == 1000) && row.collectionCycle != '0') {
          row.collectionCycle = '';
        }
        if (row.stageNum == 1 && row.collectionCycle == '0') {
          row.collectionCycle = '';
        }
        this.judgeStage(row);
      },

      //计算结束时间
      getEndDate(row) {
        if (!row.collectionCycle || row.collectionCycle == '0') return;
        let assetTarget = this.selfAssetsList.filter(item => item.assetKey == row.shopKey);
        let asset = assetTarget && assetTarget.length > 0 ? assetTarget[0] : {};
        row.endList = [];

        if (this.pageName == 'shareRentList' || this.$route.query.contractType == 'WRSB') {
          //分成租金 和 无人设备合同 没有资产
          let endDate = new Date().getTime() + 1000 * 60 * 60 * 24 * 365 * 2;
          this.getEndDateFn(row.rentStartDate, endDate, row.endList);
        } else {
          if (asset.rentEndDate && row.collectionCycle) {
            this.getEndDateFn(row.rentStartDate, asset.rentEndDate || '', row.endList);
          }
        }
        let collectionCycle = row.collectionCycle;
        let list = [];
        //按周期组装数据
        row.endList.forEach((item, index) => {
          let num = index + 1;
          if (num % collectionCycle == 0) {
            list.push(item);
          }
        });
        row.endList = list;
      },

      //计算结束时间计算部分
      /**
        规则：
        A 当前开始时间所在月份的最大值（28，29，30，31）, B 当前时间的天数位的值
        1.开始时间是1月份或者2月份时，A - B <= 3时，结束时间的天数位 = 下一月份的天数位最大值 - 差值（A - B） - 1，年月为下一月; > 3时同规则2
        2.开始时间不是1月份或者2月份时：开始时间天数位为1时：结束时间的天数位 = 月末的天数； 不为1时：结束时间的天数位 = B - 1
      **/
      getEndDateFn(startTime, assetRentEndDate, endList) {
        let endMonthDay = getLastDay(startTime); //当前开始时间所在月份的最大值
        let startDay = new Date(startTime).getDate(); //当前时间的天数位的值
        let diffDay = endMonthDay - startDay; //差值（A - B）

        var y = new Date(startTime).getFullYear(); //开始时间所在年份
        var m = new Date(startTime).getMonth() + 1; //开始时间所在月份
        var d = new Date(startTime).getDate(); //开始时间所在天

        let nextYearMonth = util.getNextMonth(y + '-' + m); //获取下一月 格式：xxxx-xx
        let nextMonth = nextYearMonth.split('-')[1];
        let endNextMonthDay = getLastDay(nextYearMonth); //下一月的最大值
        let nextDay = '';
        let nextStartDate = ''; //下一个开始时间
        let endtDate = ''; //当前的结束时间

        function calculateDay() {
          if (d == 1) {
            endtDate = y + '-' + m + '-' + endMonthDay;
            if (m == 12) {
              nextStartDate = y + 1 + '-1-1';
            } else {
              nextStartDate = y + '-' + (m + 1) + '-1';
            }
          } else {
            endtDate = nextYearMonth + '-' + (d - 1);
            nextStartDate = nextYearMonth + '-' + d;
          }
        }

        if (nextMonth == 2 || nextMonth == 3) {
          if (diffDay <= 3) {
            endtDate = nextYearMonth + '-' + (endNextMonthDay - diffDay - 1);
            nextStartDate = nextYearMonth + '-' + (endNextMonthDay - diffDay);
          } else {
            calculateDay();
          }
        } else {
          calculateDay();
        }

        if (new Date(assetRentEndDate).getTime() >= new Date(endtDate).getTime()) {
          endList.push(new Date(endtDate).getTime());
          this.getEndDateFn(nextStartDate, assetRentEndDate, endList);
        }
      },

      //选择资产变化
      setAssetArea(row) {
        this.setAssetTxt(row);
        row.rentStartDate = '';
        row.rentEndDate = '';
        this.setMoney(row, 'unit');
        this.getGuideUnitPrice(row);
        this.getEndDate(row);
      },

      //得到指导单价
      async getGuideUnitPrice(row) {
        let res = await apiGetGuideUnitPrice({ assetsCode: row.shopCode });
        if (res.rows && res.rows.length > 0) {
          row.guideUnitPrice = res.rows[0].rentGuidePrice || '';
        }
      },

      //得到所选资产面积
      getAssetArea(assetKey) {
        let area = 0;
        this.selfAssetsList.forEach(item => {
          if (assetKey == item.assetKey) {
            area = item.assetArea;
          }
        });
        return area;
      },

      //为大于第一阶段的阶段赋值首次付款时间
      setFirstPaymentDate(list) {
        let firstPaymentDate = '';
        list.forEach(item => {
          if (item.stageNum != 0 && item.firstPaymentDate) {
            firstPaymentDate = item.firstPaymentDate;
          }
        });
        list.forEach(item => {
          if (!item.firstPaymentDate && item.stageNum != 0 && item.stageNum != 1) {
            item.firstPaymentDate = firstPaymentDate;
          }
        });
      },

      //计算固定金额 单价
      setMoney(row, type) {
        if (this.$route.query.contractType == 'ZL') {
          row.assetArea = this.getAssetArea(row.shopKey);
        }
        //租赁合同：面积(分成租金的面积是所有选择资产的面积之和)  无人设备合同：设备个数
        let unitField = 0;
        if (this.$route.query.contractType == 'ZL') {
          if (this.pageName == 'shareRentList') {
            unitField = this.getAllAssetArea();
          } else {
            unitField = row.assetArea;
          }
        } else {
          unitField = this.provideObj.deviceNum || 0;
        }

        let resultNum = 0;

        if (type == 'unit') {
          if (row.fixedUnit == 'rent_fixed_day_unit') {
            resultNum = Calculate.setFixPriceByDay(row.calculateUnitPrice, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_month_unit') {
            resultNum = Calculate.setFixPriceByMonth(row.calculateUnitPrice, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_year_unit') {
            resultNum = Calculate.setFixPriceByYear(row.calculateUnitPrice, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_total_unit') {
            resultNum = Calculate.setFixPriceAll(row.calculateUnitPrice, row.calculateUnit, unitField, row.rentStartDate, row.rentEndDate);
          }
          row.fixedPriceIncludeTax = Number(resultNum) ? Number(resultNum).toFixed(2) : '';
          row.fixedPriceExcludeTax = accMul(row.fixedPriceIncludeTax || 0, 1 - this.rate).toFixed(2);
        } else {
          row.fixedPriceExcludeTax = accMul(row.fixedPriceIncludeTax || 0, 1 - this.rate).toFixed(2);
          if (row.fixedUnit == 'rent_fixed_day_unit') {
            resultNum = Calculate.setUnitPriceByDay(row.fixedPriceIncludeTax, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_month_unit') {
            resultNum = Calculate.setUnitPriceByMonth(row.fixedPriceIncludeTax, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_year_unit') {
            resultNum = Calculate.setUnitPriceByYear(row.fixedPriceIncludeTax, row.calculateUnit, unitField);
          } else if (row.fixedUnit == 'rent_fixed_total_unit') {
            resultNum = Calculate.setUnitPriceAll(row.fixedPriceIncludeTax, row.calculateUnit, unitField, row.rentStartDate, row.rentEndDate);
          }
          row.calculateUnitPrice = Number(resultNum) ? Number(resultNum).toFixed(2) : '';
        }
      },

      //初始化阶段options
      initStageList() {
        this.stageList.push({ key: 0, label: '首期' });
        this.stageList.push({ key: 1, label: '周期性' });
        // for (let i = 1; i < 30; i++) {
        //   this.stageList.push({ key: i, label: `第${i}阶段` });
        // }
        this.stageList.push({ key: 1000, label: '末期' });
      },

      //判断是否存在此阶段
      judgeStage(row) {
        let num = 0;
        let list = this.tableList.filter(item => item.shopKey === row.shopKey);
        list.forEach(item => {
          if (item.stageNum === row.stageNum && row.stageNum != 1) {
            num++;
          }
        });
        if (num > 1) {
          row.stageNum = '';
        }
      },

      //自动填充首次付款时间
      fillFirstPaymentDate() {
        let noOnceList = this.tableList.filter(item => item.collectionCycle != '0');
        if (!noOnceList[0].firstPaymentDate) {
          this.$message.warning('请填写周期性付款的第一期的‘首次付款时间’');
          return;
        }
        noOnceList.forEach((item, index) => {
          if (item.rentStartDate && item.rentEndDate && index > 0) {
            let judgeDayObj = monthDayDiff(item.rentStartDate, item.rentEndDate); //时间差值
            let differenceVal = judgeDayObj.year * 12 + judgeDayObj.month + 1;
            item.firstPaymentDate = dayjs(noOnceList[index - 1].firstPaymentDate).add(differenceVal, 'month');
            item.collectionCycle = noOnceList[index - 1].collectionCycle;
          }
        });
      },

      //保存
      saveFn() {
        let lock = true;
        if (this.tableList.length > 0) {
          lock = this.judgeTimeContin();
        }
        let res = { [this.pageName]: this.tableList };
        return lock ? res : false;
      },

      //保存校验同资产开始时间的连续性
      judgeTimeContin() {
        let dataArr = []; //按shopkey分组的数据
        let list = JSON.parse(JSON.stringify(this.tableList));
        //排除不是阶段不是周期性的
        lodash.remove(list, function (item) {
          return item.stageNum != 1;
        });

        //按照shoekey进行分组 this.pagename == "shareRentList" 或者 无人设备合同 时分成租金，没有资产，所以默认一组
        if (this.pagename == 'shareRentList' || this.$route.query.contractType == 'WRSB') {
          dataArr[0] = { list: [] };
          list.map(mapItem => {
            dataArr[0].list.push(mapItem);
          });
        } else {
          list.map(mapItem => {
            if (dataArr.length == 0) {
              dataArr.push({ shopKey: mapItem.shopKey, list: [mapItem] });
            } else {
              let res = dataArr.some(item => {
                if (item.shopKey == mapItem.shopKey) {
                  item.list.push(mapItem);
                  return true;
                }
              });
              if (!res) {
                dataArr.push({ shopKey: mapItem.shopKey, list: [mapItem] });
              }
            }
          });
        }

        //分组进行判断时间的连续性，有不符合的直接return false
        for (let i = 0; i < dataArr.length; i++) {
          let item = dataArr[i];
          for (let j = 0; j < item.list.length; j++) {
            let current = item.list[j];
            if (j > 0) {
              if (this.formDataDate(current.rentStartDate) != this.getPusOneDay(item.list[j - 1].rentEndDate)) {
                this.$message.warning('请检查' + this.title + '的"' + current.shopName + '"的时间连续性!');
                return false;
              }
            }
          }
        }
        return true;
      },

      //获取所有资产的面积
      getAllAssetArea() {
        let allNum = 0;
        this.selfAssetsList.forEach(item => {
          allNum = accAdd(allNum, item.assetArea);
        });
        return allNum || 0;
      },

      //返回传入日期加1天的日期
      getPusOneDay(date) {
        return dayjs(date).add(1, 'day').format('YYYY-MM-DD');
      },
    },

    created() {
      this.getRateList();
      this.initStageList();
    },
  };
</script>
<style lang="scss" scoped>
  ::v-deep .el-collapse-item__header {
    font-weight: 700;
    border: none;
  }
</style>
